package com.koudai.reader;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.koudai.reader.android.R;
import com.koudai.reader.conponment.ListViewAdapter;
import com.koudai.reader.util.HttpUtils;
import com.koudai.reader.vo.Book;
import com.koudai.reader.vo.EndUser;

public class CateBookListActivity extends Activity implements OnScrollListener {

    public static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(1);
    private ListView bookList;
    private ListViewAdapter mListViewAdapter;
    private TextView title;

    private RelativeLayout mLoadLayout;
    private RelativeLayout mLoadFailedlayout;

    private int mLastItem = 0;
    private int mCount = 20;
    private LayoutInflater maininflater;

    private String cateName;
    private int startPosition;
    
    private boolean isEnd;// 判断是否还有数据，用于分页
    
    private TextView score;
    private ImageView isVip;
    private ImageView back;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.cate_book_list);
        cateName = getIntent().getStringExtra("cateName");
        title = (TextView)findViewById(R.id.title);
        title.setText(cateName);
        
        bookList = (ListView) findViewById(R.id.list);
        mListViewAdapter = new ListViewAdapter(this, internalhandler);

        maininflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

        mLoadLayout = (RelativeLayout) maininflater.inflate(R.layout.loadpage, null);

        mLoadLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                threadPool.schedule(new AppListHttpRequest(), 100, TimeUnit.MILLISECONDS);
            }
        });

        mLoadFailedlayout = (RelativeLayout) maininflater.inflate(R.layout.load_failed_page, null);

        mLoadFailedlayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                bookList.removeFooterView(mLoadFailedlayout);
                bookList.addFooterView(mLoadLayout);
                threadPool.schedule(new AppListHttpRequest(), 100, TimeUnit.MILLISECONDS);
            }
        });
        bookList.addFooterView(mLoadLayout);
        bookList.setAdapter(mListViewAdapter);
        bookList.setOnScrollListener(this);
        
        back = (ImageView)findViewById(R.id.back);
        back.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
            
                finish();
            }
        });

    }

    public void onScroll(AbsListView view, int mFirstVisibleItem, int mVisibleItemCount, int mTotalItemCount) {

        mLastItem = mFirstVisibleItem + mVisibleItemCount;

        if (mListViewAdapter.count >= mCount) {
            bookList.removeFooterView(mLoadLayout);
        }

    }

    public void onScrollStateChanged(AbsListView view, int mScrollState) {
        // **
        // 当ListView滑动到最后一条记录时这时，我们会看到已经被添加到ListView的"加载项"布局， 这时应该加载剩余数据。
/*        Log.d("999", "isEnd:" + isEnd);
        Log.d("999", "mLastItem:" + mLastItem);
        Log.d("999", "mListViewAdapter.count:" + mListViewAdapter.count);
        Log.d("999", "mScrollState:" + mScrollState);
        Log.d("999", "OnScrollListener.SCROLL_STATE_IDLE:" + OnScrollListener.SCROLL_STATE_IDLE);
        */
        if (mLastItem == mListViewAdapter.count && mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            if (!isEnd) {
                startPosition += 20;
                threadPool.schedule(new AppListHttpRequest(), 0, TimeUnit.MILLISECONDS);
                Log.d("999", "sub page request, start:" + startPosition);
            } else {
                Toast.makeText(CateBookListActivity.this, "厉害，居然逛书逛到底了", Toast.LENGTH_LONG).show();
            }
        }
        Log.d("999", "==========================");

    }

    class AppListHttpRequest implements Runnable {

        @Override
        public void run() {

            try {
                final List<Book> bookData = HttpUtils.getListByCate(cateName, startPosition);

                if (bookData != null && bookData.size() > 0) {
                    isEnd = false;
                    internalhandler.post(new Runnable() {

                        @Override
                        public void run() {
                            Iterator<Book> iterator = bookData.iterator();

                            mListViewAdapter.count = startPosition;
                            while (iterator.hasNext()) {
                                Book book = iterator.next();
                                mListViewAdapter.bookDataList.put(mListViewAdapter.count++, book);
                            }

                            bookList.removeFooterView(mLoadLayout);
                            mListViewAdapter.notifyDataSetChanged();
                        }
                    });
                } else {
                    isEnd = true;
                    internalhandler.post(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(CateBookListActivity.this, "厉害，居然逛书逛到底了", Toast.LENGTH_LONG).show();
                        }
                    });
                }
                
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                sendMsg(100);
            }
        }
    }

    private void sendMsg(int flag) {
        Message msg = new Message();
        msg.what = flag;
        internalhandler.sendMessage(msg);
    }

    private Handler internalhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 定义一个Handler，用于处理下载线程与UI间通讯
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {

                case 100:
                    // app list 加载失败
                    bookList.removeFooterView(mLoadLayout);
                    bookList.addFooterView(mLoadFailedlayout);
                    break;
                case 1:
                    //更新积分
                    if (CateBookListActivity.this.getParent() instanceof BookCityActivity) {
                       ((BookCityActivity) CateBookListActivity.this.getParent()).score.setText(EndUser.getInstance().getGlodStr());
                    }
                }
            }
            super.handleMessage(msg);
        }
    };

    protected void onResume() {
        super.onResume();
        score = (TextView) findViewById(R.id.score);
        score.setText(EndUser.getInstance().getGlodStr());
        
        isVip = (ImageView) findViewById(R.id.vip);
        if (EndUser.getInstance().isVip()) {
            isVip.setVisibility(View.VISIBLE);    
        } else {
            isVip.setVisibility(View.INVISIBLE);    
        }
        threadPool.schedule(new AppListHttpRequest(), 0, TimeUnit.MILLISECONDS);
    };

}
